package com.server;

/**
 * @author Ngoc Tan
 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.sql.Timestamp;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.server.constants.CONSTANTS;
import com.server.db.DatabaseManager;
import com.server.db.DatabaseUtils;

public class MainServer
{
	private static final int PORT = 1234;

	public static Logger logger = Logger.getLogger("Server");

	public static void main(String[] args) throws IOException
	{
		// System.out.println("Starting server..");
		logger.info("Starting server..");

		// testDB();

		testDBVending();
		initDB();

		IoAcceptor acceptor = new NioSocketAcceptor();

		logger.info("Add Logging Filter..");
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());

		logger.info("Add Protocol Codec Filter..");
		acceptor.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(
						Charset.forName("UTF-8"))));

		logger.info("Add handler..");
		acceptor.setHandler(new ServerHandler());

		logger.info("Add config..");
		acceptor.getSessionConfig().setReadBufferSize(2048);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

		logger.info("Listening on port " + PORT);
		acceptor.bind(new InetSocketAddress(PORT));

	}

	@SuppressWarnings("unused")
	private static void testDB()
	{

		DatabaseManager.open();

		DatabaseManager.createTableIfNotExist("animal",
				"id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
						+ "PRIMARY KEY (id),"
						+ "name CHAR(40), category CHAR(40)");

		DatabaseManager.insert("animal", "name, category", "'snake', 'reptile'");

		DatabaseManager.close();

	}

	private static void testDBVending()

	{
		DatabaseManager.open();

		DatabaseUtils.createTableAccount();
		DatabaseUtils.createTableBox();
		DatabaseUtils.createTableMachine();
		DatabaseUtils.createTableProduct();
		DatabaseUtils.createTableProductPutIn();
		DatabaseUtils.createTableProductSell();
		DatabaseUtils.createTableBoxInventory();

		DatabaseManager.close();
	}

	private static void initDB()
	{
		/* Initiate data */
		int totalBox = 40;
		String codeVM = "M01";

		long time = System.currentTimeMillis();

		Timestamp timestamp = new Timestamp(time);

		/* Insert machine data */
		String columnSet = CONSTANTS.MACHINE.COLUMN_AMOUNT_BOX + ", "
				+ CONSTANTS.MACHINE.COLUMN_CODE + ", "
				+ CONSTANTS.MACHINE.COLUMN_DATE_CREATED + ", "
				+ CONSTANTS.MACHINE.COLUMN_DATE_TERMINATED + ", "
				+ CONSTANTS.MACHINE.COLUMN_GROUP + ", "
				+ CONSTANTS.MACHINE.COLUMN_LATITTUDE + ", "
				+ CONSTANTS.MACHINE.COLUMN_LOCATION_ID
				+ ", "
				+ CONSTANTS.MACHINE.COLUMN_LONGITUDE
				+ ", "

				// + CONSTANTS.MACHINE.COLUMN_STAFF_CREATE + ", "
				// + CONSTANTS.MACHINE.COLUMN_STAFF_TERMINATE + ", "
				// + CONSTANTS.MACHINE.COLUMN_STAFF_UPDATE + ", "

				+ CONSTANTS.MACHINE.COLUMN_STATUS + ", "
				+ CONSTANTS.MACHINE.COLUMN_STATUS_RENT;
		String columnValue = totalBox + ",'" + codeVM
				+ "',?,?,0,0,0,0,1,1";

		logger.info("Inserting table machine....");
		DatabaseManager.insertReturnId(CONSTANTS.MACHINE.TABLE_NAME, columnSet,
				columnValue, new Timestamp[] { timestamp, timestamp });

		/* Insert boxes data */
		String tableName = CONSTANTS.BOX.TABLE_NAME;

		columnSet = CONSTANTS.BOX.COLUMN_ID
				+ ", "

				// + CONSTANTS.BOX.COLUMN_ACTIVE + ", "

				+ CONSTANTS.BOX.COLUMN_PRODUCT_AMOUNT + ", "
				+ CONSTANTS.BOX.COLUMN_MACHINE_CODE + ", "

				// + CONSTANTS.BOX.COLUMN_NAME + ", "

				+ CONSTANTS.BOX.COLUMN_PRODUCT_CODE + ", "
				+ CONSTANTS.BOX.COLUMN_PRODUCT_PRICE;

		for (int i = 0; i < totalBox; i++)
		{
			columnValue = (i + 1) + " ,0, '" + codeVM + "', 0, 0";

			if (columnSet != null && columnValue != null && tableName != null)
			{
				logger.info("Inserting table box....");
				DatabaseManager.insertReturnId(tableName, columnSet,
						columnValue);
			}
		}
		/* Insert accounts data */
		logger.info("Inserting table account....");

		tableName = CONSTANTS.ACCOUNT.TABLE_NAME;

		columnSet = CONSTANTS.ACCOUNT.COLUMN_ACTIVE + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_AMOUNT + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_DATE_CREATED + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_GROUP_ID + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_PASSWORD + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_PIN_CODE + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_POSITION_ID + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_STAFF_ID + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_TERMINATED + ", "
				+ CONSTANTS.ACCOUNT.COLUMN_USER_NAME;

		columnValue = "1, 0, ?, 0, 'password', 'pin', 0, '0937813357', 0, '0937813357'";

		DatabaseManager.insertReturnId(tableName, columnSet, columnValue,
				new Timestamp[] { timestamp });

		columnValue = "1, 0, ?, 0, 'password', 'pin', 0, '0942478466', 0, '0942478466'";

		DatabaseManager.insertReturnId(tableName, columnSet, columnValue,
				new Timestamp[] { timestamp });

		columnValue = "1, 0, ?, 0, 'password', 'pin', 0, '0975992243', 0, '0975992243'";

		DatabaseManager.insertReturnId(tableName, columnSet, columnValue,
				new Timestamp[] { timestamp });

		columnValue = "1, 0, ?, 0, 'password', 'pin', 0, '0903946510', 0, '0903946510'";

		DatabaseManager.insertReturnId(tableName, columnSet, columnValue,
				new Timestamp[] { timestamp });

		/* Insert products data */
		int[] prices = { 5000, 6000, 7000, 8000, 9000, 10000 };
		String[] names = { "PEPSI", "AQUAFINA", "STING", "YELLOW STING",
				"SEVENUP", "REVIVE", "TWISTER", "MIRINDA CAM", "MIRINDA XA XI",
				"COCA COLA", "LAVIE", "C2 WAITER" };

		tableName = CONSTANTS.PRODUCT.TABLE_NAME;

		columnSet = CONSTANTS.PRODUCT.COLUMN_IMAGE_PATH + ", "
				+ CONSTANTS.PRODUCT.COLUMN_PRICE_BUYING + ", "
				+ CONSTANTS.PRODUCT.COLUMN_PRICE_SELLING + ", "
				+ CONSTANTS.PRODUCT.COLUMN_CODE + ", "
				+ CONSTANTS.PRODUCT.COLUMN_GROUP_ID + ", "
				+ CONSTANTS.PRODUCT.COLUMN_NAME
				
		// + ", "
		// + CONSTANTS.PRODUCT.COLUMN_PRODUCT_SUPPLIER_ID
				
				;

		for (int index = 0; index < names.length; index++)
		{
			int price = prices[(int) (System.currentTimeMillis() % prices.length)];

			columnValue = "'index.png', " + price + ", " + price + ", " + index
					+ ", 0, '" + names[index] + "'";

			DatabaseManager.insertReturnId(tableName, columnSet, columnValue);
		}
	}
}
